<template>
    <div>
        <div class="searchhead">
            <div class="searchone">
                <div class="khname">
                    <p class="namecs">客户姓名</p>
                    <el-input v-model="queryInfo.name" style="width: 240px; margin-left: 10px; margin-right: 30px;"
                        placeholder="请输入客户姓名" />
                </div>
                <div class="khname">
                    <p class="namecs">客户手机</p>
                    <el-input v-model="queryInfo.phone" style="width: 240px; margin-left: 10px; margin-right: 30px;"
                        placeholder="请输入客户手机号码" />
                </div>
                <div class="khname">
                    <p class="namecs">归属人</p>
                    <el-input v-model="queryInfo.owner" style="width: 240px; margin-left: 10px; margin-right: 30px;"
                        placeholder="请输入线索归属人" />
                </div>
                <div class="khname">
                    <p class="namecs">渠道来源</p>
                    <el-select v-model="queryInfo.channelId" placeholder="渠道来源"
                        style="width: 240px; margin-left: 10px; margin-right: 30px;">
                        <el-option v-for="item in channelList" :key="item.channelId" :label="item.channelName"
                            :value="item.channelId" />
                    </el-select>
                </div>
            </div>
            <div class="searchtwo">
                <div class="khname">
                    <p class="namecs">线索状态</p>
                    <el-select v-model="queryInfo.status" placeholder="线索状态"
                        style="width: 240px; margin-left: 10px; margin-right: 30px;">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"
                            :disabled="item.disabled" />
                    </el-select>
                </div>
                <div class="khname">
                    <p class="namecs">跟进时间</p>
                    <div class="block" style="margin-left: 10px;">
                        <el-date-picker v-model="queryInfo.fundTimeArray" type="daterange" range-separator="-"
                            start-placeholder="开始日期" end-placeholder="结束日期" />
                    </div>
                </div>
                <div class="btntwo">
                    <el-button type="primary" :icon="Search" @click="getData">搜索</el-button>
                    <el-button :icon="Refresh" @click="reset">重置</el-button>
                </div>
            </div>
        </div>
        <div class="secbtn">
            <el-button type="primary" :icon="Plus" plain @click="openDialog">新增</el-button>
            <el-button type="success" :icon="Edit" @click="editClue">修改</el-button>
            <el-button type="danger" :icon="Delete" @click="deleteClue">删除</el-button>
            <el-button type="warning" :icon="Download" @click="exportToExcel">导出</el-button>
        </div>
        <div class="datatable">
            <el-table :data="formattedTableData" border style="width: 100%" @selection-change="handleSelectionChange"
                @select="handleSelect" @select-all="handleSelectAll">
                <el-table-column type="selection" width="55" />
                <el-table-column property="clueId" label="线索编号" width="120" />
                <el-table-column property="name" label="客户姓名" width="120" />
                <el-table-column property="phone" label="手机号码" width="140" />
                <el-table-column property="channelName" label="渠道来源" width="140" />
                <el-table-column property="createTime" label="创建时间" width="160" />
                <el-table-column property="createBy" label="线索归属" width="100" />
                <el-table-column property="status" label="线索状态" width="100">
                    <template #default="scope">
                        <!-- <el-tag type="warning" v-if="scope.row.status == 1">伪线索</el-tag> -->
                        <el-tag type="primary" v-if="scope.row.status == 1">已分配</el-tag>
                        <el-tag type="warning" v-if="scope.row.status == 4">伪线索</el-tag>
                        <el-tag type="success" v-if="scope.row.status == 2">跟进中</el-tag>
                        <p v-else></p>
                    </template>
                </el-table-column>
                <el-table-column property="nextTime" label="下次跟进时间" width="200" />
                <el-table-column label="操作" width="280">
                    <template #default="scope">
                        <el-button type="primary" plain :icon="View"
                            @click="handleEdit(scope.$index, scope.row)">查看</el-button>
                        <el-button v-if="scope.row.status == 1" type="primary" plain :icon="Pointer"
                            @click="fp(scope.$index, scope.row)">分配</el-button>
                        <el-button v-if="scope.row.status == 1 || 2" type="primary" plain :icon="Pointer"
                            @click="gj(scope.$index, scope.row)">跟进</el-button>
                        <!-- <el-button v-if="scope.row.status == 0" type="primary" plain :icon="TopRight"
                            @click="handleEdit(scope.$index, scope.row)">跟进</el-button> -->
                        <!-- <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
                        <!-- <el-button size="small" type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <Pagination :total="total" @changePage="setPage" @changeRows="setRows"></Pagination>

        <!-- 新增修改模态框 -->
        <el-dialog v-model="dialogFormVisible" :title="edisId == '' ? '添加线索' : '修改线索'" width="500">
            <el-form :model="form">
                <el-form-item label="手机号码">
                    <el-input v-model="form.phone" style="width: 240px" placeholder="请输入手机号码" />
                </el-form-item>
                <el-form-item label="客户姓名">
                    <el-input v-model="form.name" style="width: 240px" placeholder="请输入客户姓名" />
                </el-form-item>
                <el-form-item label="渠道来源">
                    <el-select v-model="form.channelId" placeholder="渠道来源" style="width: 240px; margin-right: 30px;">
                        <el-option v-for="item in channelList" :key="item.channelId" :label="item.channelName"
                            :value="item.channelId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="活动信息">
                    <el-select v-model="form.activityId" placeholder="活动信息" style="width: 240px; margin-right: 30px;">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"
                            :disabled="item.disabled" />
                    </el-select>
                </el-form-item>
                <el-form-item label="客户性别">
                    <el-radio-group v-model="form.gender">
                        <el-radio :label="1" :value="1" size="large">男</el-radio>
                        <el-radio :label="2" :value="2" size="large">女</el-radio>
                        <el-radio :label="0" :value="0" size="large">未知</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="客户年龄">
                    <el-input-number v-model="form.age" :min="1" :max="150" />
                </el-form-item>
                <el-form-item label="微信号">
                    <el-input v-model="form.weixin" style="width: 240px" placeholder="请输入微信号码" />
                </el-form-item>
                <el-form-item label="QQ号">
                    <el-input v-model="form.qq" style="width: 240px" placeholder="请输入QQ号码" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button v-if="edisId === ''" type="primary" @click="tjdialogFormVisible">
                        确定
                    </el-button>
                    <el-button v-else type="primary" @click="editdialogFormVisible">
                        编辑
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 分配模态框 -->
        <el-dialog v-model="dialogFormVisiblefp" title="分配线索" width="500">
            <el-form :model="form">
                <el-form-item label="归属部门" :label-width="formLabelWidth">
                    <el-select v-model="assignForm.deptId" placeholder="请选择归属部门">
                        <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName"
                            :value="item.deptId" />
                    </el-select>
                </el-form-item>

                <el-form-item label="分配给" :label-width="formLabelWidth">
                    <el-tree-select v-model="assignForm.departmentId" :data="transformedData"
                        :render-after-expand="true" check-strictly=true style="width: 240px" placeholder="请选择归属部门"
                        @change="getArea" />
                    <!-- <el-select v-model="assignForm.assignId" placeholder="请选择归属部门">
                        <el-option :label="deptList[0].leader" :value="deptList[0].leader" />
                    </el-select> -->
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="fpyes">
                        确定
                    </el-button>
                    <el-button @click="dialogFormVisiblefp = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { onMounted, ref, computed, reactive } from 'vue';
import { Search, Refresh, Plus, Edit, Delete, Download, View, Pointer, TopRight } from '@element-plus/icons-vue';
import { ElTable, ElMessage } from 'element-plus';

import { getClueData, getChannelData, addClue, delClue, getChannelDataByid, editClueaxios, getDeptList, getDeptListselect } from '@/api/clue/getIndex';

import Pagination from "./Pagination.vue";
const total = ref(0);
const queryInfo = ref({
    pageNum: 1,
    pageSize: 10,
    name: "",
    phone: "",
    owner: "",
    status: "",
    channelId: "",
    fundTimeArray: [],
    beginTime: "",
    endTime: ""
});
// const handleChannelChange = (val: any) => {
//     console.log('Channel changed to:', val);
//     // Add your logic here to handle the change
// };
// 分配
function transformData(data) {
    return data.map(item => {
        const newItem = { ...item };
        newItem.value = newItem.id;
        delete newItem.id;
        if (newItem.children) {
            newItem.children = transformData(newItem.children);
        }
        return newItem;
    });
}

const assignForm = ref({
    deptId: 0,
    type: 1,
    userId: 0,
    userName: "",
    nickName: "",
    departmentId: "",
    assignId: 0
})
const deptList = ref([]);
const deptListselect = ref([]);
const fpyes = () => {
    dialogFormVisiblefp.value = false;
    ElMessage.success("分配成功");
}
const dialogFormVisiblefp = ref(false);
const formLabelWidth = '140px';
const getdept = () => {
    getDeptList().then((res: any) => {
        if (res.code !== 200) return ElMessage.error('查询部门失败');
        console.log(res);
        deptList.value = res.data;
    });
};
const getdeptselect = () => {
    getDeptListselect().then((res: any) => {
        if (res.code !== 200) return ElMessage.error('查询部门失败');
        console.log(res);
        deptListselect.value = res.data;
    });
};
// ----------------------------------------------
// 导出

// 导出到Excel
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
function exportToExcel() {
    const ws = XLSX.utils.json_to_sheet(tableData.value);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

    const wbout = XLSX.write(wb, { bookType: "xlsx", type: "binary" });
    function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
    }

    saveAs(
        new Blob([s2ab(wbout)], { type: "application/octet-stream" }),
        "data.xlsx"
    );
}
// ----------------------------------------------
const setPage = (n: number) => {
    console.log(n);

    queryInfo.value.pageNum = n;
    getData();
};
const setRows = (n: number) => {
    console.log(n);
    queryInfo.value.pageSize = n;
    getData();
};

const searchFormData = reactive({
    name: "",
    phone: "",
    createBy: "",
    channelId: "",

});
let clueIds = ref([]);
const handleSelectionChange = (val: any) => {
    // console.log('选中的数据:', val);
    // console.log(val);
    clueIds.value = val.map((item: any) => item.clueId);
    console.log(clueIds.value);

};
const phone = ref("");

const deleteClue = () => {
    if (clueIds.value.length === 0) return ElMessage.error("请选择要删除的数据");
    delClue(clueIds.value).then((res: any) => {
        if (res.code === 200) {
            console.log(res);
            getData();
            ElMessage.success("删除成功");
        }

    });
};
let edisId = ref("");
const editClue = () => {
    if (clueIds.value.length === 0) return ElMessage.error("请选择要修改的数据");
    console.log(clueIds.value[0]);
    edisId.value = clueIds.value[0];
    dialogFormVisible.value = true;
    getChannelDataByid(edisId.value).then((res: any) => {
        console.log(res);
        form.activityId = '';
        form.age = res.data.age;
        form.channelId = res.data.channelId;
        form.clueId = res.data.clueId;
        form.createBy = "";
        form.createTime = res.data.createTime;
        form.delFlag = 0;
        form.endTime = "";
        form.failCount = res.data.failCount;
        form.gender = 1;
        form.level = 0;
        form.name = res.data.name;
        form.nextTime = "";
        form.phone = res.data.phone;
        form.qq = res.data.qq;
        form.remark = 0;
        form.status = res.data.status;
        form.subject = 0;
        form.transfer = true;
        form.updateBy = res.data.updateBy;
        form.updateTime = "";
        form.weixin = res.data.weixin;
    });
};

interface Clue {
    clueId: string;
    name: string;
    phone: string;
    channelName: string;
    createTime: string;
    createBy: string;
    status: string;
    nextTime: string;
}
const tableData = ref<Clue[]>([]);
const channelList = ref([]);

const formattedTableData = computed(() => {
    return tableData.value.map(item => ({
        ...item,
        createTime: item.createTime.replace('T', ' '),
        nextTime: item.nextTime.replace('T', ' '),
    }));
});

const getData = () => {
    getClueData(queryInfo.value).then((res: any) => {
        if (res.code !== 200) return ElMessage.error("查询列表失败");
        console.log(res);
        tableData.value = res.rows;
        total.value = res.total;
    });
};
const getChannelList = () => {
    getChannelData().then((res: any) => {
        if (res.code !== 200) return ElMessage.error("查询列表失败");
        // console.log(res);
        channelList.value = res.data;
    });
}

onMounted(() => {
    getData();
    getChannelList();
    getdept();
    getdeptselect();
});
const router = useRouter();

const handleEdit = (index: number, row: Clue) => {
    console.log('编辑', index, row);
    router.push({ path: `/clue/clueDetail/${row.clueId}` });
    // mhsearchdata(row.clueId).then((res: any) => {
    //     console.log(res);
    // });
};

const handleDelete = (index: number, row: Clue) => {
    console.log('删除', index, row);
};

const dialogFormVisible = ref(false);

const tjdialogFormVisible = () => {
    console.log(form);
    addClue(form).then((res: any) => {
        if (res.code !== 200) return ElMessage.error("查询列表失败");
        // ElMessage.success("添加成功");
        getData();
        dialogFormVisible.value = false;
        console.log(res);
    });
};
const editdialogFormVisible = () => {
    editClueaxios(form).then((res: any) => {
        if (res.code !== 200) return ElMessage.error("更新失败");
        console.log(res);
        getData();
        dialogFormVisible.value = false;
    });
}
const openDialog = () => {
    edisId.value = '';
    form.activityId = '';
    form.age = 0;
    form.channelId = '';
    form.clueId = 0;
    form.createBy = "";
    form.createTime = "";
    form.delFlag = 0;
    form.endTime = "";
    form.failCount = 0;
    form.gender = 1;
    form.level = 18;
    form.name = "";
    form.nextTime = "";
    form.phone = "";
    form.qq = "";
    form.remark = 0;
    form.status = 1;
    form.subject = 0;
    form.transfer = true;
    form.updateBy = "";
    form.updateTime = "";
    form.weixin = "";
    dialogFormVisible.value = true;
};
const form = reactive({
    activityId: '',
    age: 0,
    channelId: '',
    clueId: 0,
    createBy: "",
    createTime: "",
    delFlag: 0,
    endTime: "",
    failCount: 0,
    gender: 1,
    level: 18,
    name: "",
    nextTime: "",
    phone: "",
    qq: "",
    remark: 0,
    status: 1,
    subject: 0,
    transfer: true,
    updateBy: "",
    updateTime: "",
    weixin: ""
});
const fp = (val: any, value: any) => {
    // console.log(val);
    console.log(value);
    assignForm.value.deptId = value.clueId;
    dialogFormVisiblefp.value = true
    // dialogFormVisiblefp.value = true;
}
const selectedClueIds = ref<number[]>([]);

const handleSelect = (selection: Clue[]) => {
    selectedClueIds.value = selection.map(item => item.clueId);
    // console.log('选中的线索ID:', selectedClueIds.value);
};

const handleSelectAll = (selection: Clue[]) => {
    selectedClueIds.value = selection.map(item => item.clueId);
    // console.log('选中的线索ID:', selectedClueIds.value);
};
// 跟进
const gj = (val: any, value: any) => {
    console.log(value);
    router.push({ path: `/clue/clueFollow/${value.clueId}` });
};
const reset = () => {
    // 重置表单
    queryInfo.value.name = "";
    queryInfo.value.phone = "";
    queryInfo.value.owner = "";
    queryInfo.value.status = "";
    queryInfo.value.channelId = "";
    // queryInfo.value.beginTime = "",
    // queryInfo.value.endTime = "",
    // queryInfo.value.fundTimeArray = [],
};
</script>

<style lang="scss" scoped>
.searchhead {
    padding-top: 20px;
    padding-left: 30px;

    .namecs {
        font-weight: 600;
        margin-top: 5px;
    }

    .khname {
        display: flex;
    }

    .searchone {
        display: flex;
    }

    .searchtwo {
        display: flex;
        margin-top: 20px;

        .btntwo {
            margin-left: 30px;
        }
    }
}

.secbtn {
    padding-left: 20px;
    margin-top: 20px;
}

.datatable {
    padding-left: 20px;
    width: 100%;
    margin-top: 10px;
}
</style>